package com.st.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.pojo.User;
import com.st.service.RoleService;
import com.st.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(User.COL_NAME,username);
        User one = userService.getOne(qw);

        //TODO
        List<SimpleGrantedAuthority> grantedAuthorityList = new ArrayList<>();
       List<String> getroledList = roleService.getroleList(one.getId());
        for (String s : getroledList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+s);
            grantedAuthorityList.add(authority);
        }
        SecurityDetailsImpl securityDetails = new SecurityDetailsImpl(one,grantedAuthorityList);
        return securityDetails;
    }
}
